/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
  if (!grid && grid.length === 0) return 0

  let m = grid.length
  let n = grid[0].length
  let count = 0//独立的岛屿数量

  function dfs(i, j) {
    //超出边界 或 遇到"水"
    if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] === '0') return
    //沉"岛"入"水"
    grid[i][j] = '0'
    //继续向四周递归
    dfs(i - 1, j)
    dfs(i, j + 1)
    dfs(i + 1, j)
    dfs(i, j - 1)
  }

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (grid[i][j] === '1') {
        count++
        dfs(i, j)
      }
    }
  }

  return count
};